// pages/my-points/my-points.ts
import { PAGES, goToPage } from '../../../config/pages';
import userManager from '../../../utils/userManager.js';

Page({
  data: {
    totalPoints: 0,
    memberLevel: '青铜会员',
    isVip: false,
    currentLevel: {
      name: '青铜会员',
      min: 0,
      max: 4999,
    },
    nextLevel: {
      name: '白银会员',
      min: 5000,
    },
    progress: 0,
    progressText: '0/5000',
    quickActions: [
      { icon: 'fa-gift', text: '积分商城', url: PAGES.PRIZES },
      { icon: 'fa-info-circle', text: '积分规则', url: PAGES.POINTS_RULES },
    ],
    earnItems: [
      { icon: 'fa-calendar-check', text: '每日签到', points: '+10积分', color: '#00a870', action: 'checkin' },
      { icon: 'fa-upload', text: '产品信息上传', points: '+50积分/条', color: '#0052d9', action: 'upload' },
      { icon: 'fa-user-plus', text: '推荐有礼', points: '+100积分/人', color: '#e37318', action: 'invite' },
      { icon: 'fa-shield-alt', text: '身份认证', points: '+50/500积分', color: '#ed7b2f', action: 'verify' },
    ],
  },

  onLoad() {
    this.loadPointsData();
  },

  onShow() {
    // 每次显示页面时重新加载积分数据，确保数据最新
    this.loadPointsData();
  },

  // 加载积分数据
  async loadPointsData() {
    try {
      // 从用户信息中获取积分数据（integral 字段）
      const userInfo = await userManager.getUserInfo(false, false);
      const totalPoints = userInfo?.integral || 0;
      
      const currentLevel = this.getCurrentLevel(totalPoints);
      const nextLevel = this.getNextLevel(totalPoints);
      
      let progress = 0;
      let progressText = '';
      
      if (nextLevel) {
        progress = ((totalPoints - currentLevel.min) / (nextLevel.min - currentLevel.min)) * 100;
        progressText = `${totalPoints}/${nextLevel.min}`;
      } else {
        progress = 100;
        progressText = '已达最高等级';
      }

      this.setData({
        totalPoints,
        memberLevel: currentLevel.name,
        currentLevel,
        nextLevel,
        progress: Math.min(progress, 100),
        progressText,
      });
    } catch (error) {
      console.error('加载积分数据失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    }
  },

  // 获取当前等级
  getCurrentLevel(points: number) {
    const levels = [
      { name: '青铜会员', min: 0, max: 4999 },
      { name: '白银会员', min: 5000, max: 9999 },
      { name: '黄金会员', min: 10000, max: 19999 },
      { name: '白金会员', min: 20000, max: 29999 },
      { name: '钻石会员', min: 30000, max: 39999 },
      { name: '黑钻会员', min: 40000, max: Infinity },
    ];

    for (let level of levels) {
      if (points >= level.min && points <= level.max) {
        return level;
      }
    }
    return levels[0];
  },

  // 获取下一等级
  getNextLevel(points: number) {
    const levels = [
      { name: '青铜会员', min: 0, max: 4999 },
      { name: '白银会员', min: 5000, max: 9999 },
      { name: '黄金会员', min: 10000, max: 19999 },
      { name: '白金会员', min: 20000, max: 29999 },
      { name: '钻石会员', min: 30000, max: 39999 },
      { name: '黑钻会员', min: 40000, max: Infinity },
    ];

    for (let i = 0; i < levels.length - 1; i++) {
      if (points >= levels[i].min && points <= levels[i].max) {
        return levels[i + 1];
      }
    }
    return null;
  },

  // 每日签到（跳转到个人中心页面进行签到）
  dailyCheckin() {
    // 跳转到个人中心页面，由个人中心页面处理签到逻辑
    wx.switchTab({
      url: '/pages/profile/profile'
    });
  },

  // 上传产品
  uploadProduct() {
    goToPage(PAGES.PUBLISH_SELECT);
  },

  // 邀请好友
  inviteFriend() {
    goToPage(PAGES.INVITATIONS);
  },

  // 完成认证
  completeVerify() {
    goToPage(PAGES.CREATE_ENTERPRISE);
  },

  // 升级会员
  upgradeMember() {
    goToPage(PAGES.MEMBERSHIP_REGISTER);
  },

  // 快速操作
  onActionTap(e: any) {
    const { url } = e.currentTarget.dataset;
    if (url) {
      goToPage(url);
    }
  },

  // 快速赚取积分
  onEarnTap(e: any) {
    const { action } = e.currentTarget.dataset;
    
    switch (action) {
      case 'checkin':
        this.dailyCheckin();
        break;
      case 'upload':
        this.uploadProduct();
        break;
      case 'invite':
        this.inviteFriend();
        break;
      case 'verify':
        this.completeVerify();
        break;
    }
  },
});
